package com.hcy.app.api

import com.hcy.app.data.GlobalState
import com.koushikdutta.async.BuildConfig
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitManage {

    private const val BASE_URL = "http://14.103.183.219/api/" // "http://14.103.183.219/api/",  http://127.0.0.1:19000/api/
    private const val CONNECT_TIMEOUT = 5L
    private const val READ_TIMEOUT = 5L
    private const val WRITE_TIMEOUT = 5L

    private val retrofit: Retrofit by lazy { initRetrofit() }

    val apiService: ApiService = retrofit.create(ApiService::class.java)

    private fun initRetrofit(): Retrofit {
        return Retrofit.Builder().apply {
            baseUrl(BASE_URL)
            client(createOkHttpClient())
            addConverterFactory(GsonConverterFactory.create())
        }.build()
    }

    private fun createOkHttpClient(): OkHttpClient{
        val okHttpClientBuilder =OkHttpClient().newBuilder().apply {
            connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
            readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
            writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
            addInterceptor { chain ->
                val request = chain.request().newBuilder().apply {
                    // 统一添加Header
                    addHeader("Accept", "application/json")
                    addHeader("Content-Type", "application/json")
                    // 在此处添加token等认证信息
                    if ( GlobalState.CapToken!="" ){
                        addHeader("Authorization", GlobalState.CapToken)
                    }
                }.build()
                chain.proceed(request)
            }
            // 添加日志拦截器
            addInterceptor(HttpLoggingInterceptor().apply {
                level = if (BuildConfig.DEBUG) {
                    HttpLoggingInterceptor.Level.BODY
                } else {
                    HttpLoggingInterceptor.Level.NONE
                }
            })
//            addInterceptor(InterceptorForTokenRefresh()) // Token刷新拦截器[5](@ref)
            addInterceptor(InterceptorForResponse()) // 响应拦截器
        }

        return okHttpClientBuilder.build()
    }

}

